package http

import (
	"encoding/json"
	"fmt"
	"send-id-num/internal/repository"
	"time"

	"github.com/golang-jwt/jwt"
)

const saltSecret = "Geoo@123"

type UserInfo struct {
	UserId repository.UserId `json:"userId"`
	Source int               `json:"source"`
	jwt.StandardClaims
}

func GenerateUserToken(userId repository.UserId, source int) (string, error) {
	// 创建一个我们自己的声明的数据
	c := &UserInfo{
		UserId:         userId,
		Source:         source,
		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Add(time.Hour * 4).Unix()},
	}
	// 使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	return token.SignedString([]byte(saltSecret))
}

func ParseUserToken(token string) (info UserInfo, err error) {
	tokenModel, err := validateToken(token)
	if err != nil {
		return
	}

	claims := tokenModel.Claims.(jwt.MapClaims)
	b, err := json.Marshal(claims)
	if err != nil {
		return
	}
	err = json.Unmarshal(b, &info)
	return
}

func validateToken(signedToken string) (*jwt.Token, error) {
	token, err := jwt.Parse(signedToken, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected login method %v", token.Header["alg"])
		}
		return []byte(saltSecret), nil
	})
	if err != nil {
		return nil, err
	}

	return token, nil
}
